﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Win32;
using System.Security.Cryptography;


namespace TwitterWebPart.Twitter
{
    public partial class TwitterUserControl : UserControl, TwitterWebPart.Twitter.TwitterSearchUserControl
    {
        /// <WebPart Method>
        public Twitter WebPart { get; set; }
        /// </WebPart Method>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);


        }
        private static string TweetsPerPageProp()
        {
            throw new NotImplementedException();
        }
        private void BindData()
        {
            if (this.WebPart.TweetsPerPageProp == null)
            { this.WebPart.TweetsPerPageProp = 0; }
            if (this.WebPart.MaxTweetsProp == null)
            { this.WebPart.MaxTweetsProp = 0; }

            DataTable dt = new DataTable();                       /////Datatable to show results/////
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Title", typeof(string));



            if (txtboxSearch.Text == "")
            {
                gvTwitterSearch.DataSource = null;
                gvTwitterSearch.DataBind();
                lblTweets.Text = "";
                lblNewTweets.Text = "";
                txtboxSearch.Text = "";

                lblNewTweets.Text = "Please enter search term";

            }
            else
            {

                /////Retriving data from twitter/////
                int totalTweets = 0; 
                TweetStream[] tweetStreams = new TweetStream[] {
              new TweetStream("http://search.twitter.com/search.atom?q="+txtboxSearch.Text),
                                           
               };
               
                int currentTweets = 0;
                bool newTweets = false;
                foreach (TweetStream stream in tweetStreams)
                {
                    stream.Refresh();

                    foreach (Tweet tweet in stream.Tweets)
                    {                                          
                        /////Matching results from twitter witt user input/////
                        if (this.WebPart.MaxTweetsProp != 0)
                        {
                            if (dt.Rows.Count < (Convert.ToInt32(this.WebPart.MaxTweetsProp.ToString())))
                            {
                                dt.Rows.Add(tweet.Author.Name, tweet.Title);

                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            dt.Rows.Add(tweet.Author.Name, tweet.Title);
                        }

                        newTweets = true;
                        totalTweets++;
                        currentTweets++;

                    }
                    /////showing tweets/////
                    if (newTweets)                                   
                    {
                        lblTweets.Text = "Showing " + totalTweets + " " + "Tweets";
                        
                    }
                    else
                    {
                        lblTweets.Text = " ";
                    }
                    
                    /////refreshing results after 5 minutes interval/////
                    
                    if (this.WebPart.TweetsPerPageProp == 0)
                    { gvTwitterSearch.AllowPaging = false; }
                    else
                    {
                        gvTwitterSearch.AllowPaging = true;
                        gvTwitterSearch.PageSize = Convert.ToInt32(this.WebPart.TweetsPerPageProp.ToString());
                    }

                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            ViewState["Data"] = dt;
                            Label4.Text = dt.Rows.Count.ToString();
                            /////binding datatable with gridview
                            gvTwitterSearch.DataSource = dt;                        
                            gvTwitterSearch.DataBind();
                        }
                        else
                        {
                            gvTwitterSearch.DataSource = null;
                            gvTwitterSearch.DataBind();
                        }

                    }
                    lblNewTweets.Text = "";
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string Key = EncryptText("Expiration");
                string ExpirationDate = Read(Key);
                if (ExpirationDate == null)
                {
                    //Create Registry
                    ExpirationDate = EncryptText(System.DateTime.Now.AddMinutes(5).ToString());
                    Write(Key, ExpirationDate);
                }
                ExpirationDate = DecryptText(ExpirationDate);
                //Compare Dates
                DateTime ExpiryDate = Convert.ToDateTime(ExpirationDate);
                TimeSpan ts = ExpiryDate.Subtract(System.DateTime.Now);
                if (ts.Minutes >= 0)
                {
                    //run normal process
                    txtboxSearch.Enabled = true;
                    btnSearch.Enabled = true;
                    btnRefresh.Enabled = true;
                    btnClear.Enabled = true;
                    btnkey.Visible = false;
                    txtKey.Visible = false;

                }
                else
                {
                    //display message
                    txtboxSearch.Enabled = false;
                    btnSearch.Enabled = false;
                    btnRefresh.Enabled = false;
                    btnClear.Enabled = false;
                    lblExpire.Text = "Warning: " + "Your trial period has expired. Please enter key to activate!";

                }
            }
            catch
            {
                txtboxSearch.Enabled = false;
                btnSearch.Enabled = false;
                btnRefresh.Enabled = false;
                btnClear.Enabled = false;
                lblExpire.Text = "Warning: " + "Your trial period has expired. Please enter key to activate!";
            }

        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }
        protected void gvTwitterSearch_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void gvTwitterSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvTwitterSearch.PageIndex = e.NewPageIndex;
            if (ViewState["Data"] != null)
            {
                DataTable dt = (DataTable)ViewState["Data"];
                gvTwitterSearch.DataSource = dt;
            }
            gvTwitterSearch.DataBind();
        }
        protected void btnClear_Click(object sender, EventArgs e)
        {
            gvTwitterSearch.DataSource = null;
            gvTwitterSearch.DataBind();
            lblTweets.Text = "";
            lblNewTweets.Text = "";
            txtboxSearch.Text = "";

        }
        protected void btnRefresh_Click(object sender, EventArgs e)
        {

            if (this.WebPart.TweetsPerPageProp == null)
            { this.WebPart.TweetsPerPageProp = 0; }
            if (this.WebPart.MaxTweetsProp == null)
            { this.WebPart.MaxTweetsProp = 0; }

            DataTable dt = new DataTable();                       /////Datatable to show results/////
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Title", typeof(string));



            if (txtboxSearch.Text == "")
            {
                gvTwitterSearch.DataSource = null;
                gvTwitterSearch.DataBind();
                lblTweets.Text = "";
                lblNewTweets.Text = "";
                txtboxSearch.Text = "";

                lblNewTweets.Text = "Please enter search term";
            }
            else
            {


                int totalTweets = 0;                                 /////Retriving data from twitter/////
                TweetStream[] tweetStreams = new TweetStream[] {
               new TweetStream("http://search.twitter.com/search.atom?q="+txtboxSearch.Text),
              
            };
               
                int currentTweets = 0;
                bool newTweets = false;
                foreach (TweetStream stream in tweetStreams)
                {
                    stream.Refresh();
                    foreach (Tweet tweet in stream.Tweets)
                    {                                           
                        /////Matching results from twitter witt user input/////
                        /////adding results in datarow/////
                        if (this.WebPart.MaxTweetsProp != 0)
                        {
                            if (dt.Rows.Count < (Convert.ToInt32(this.WebPart.MaxTweetsProp.ToString())))
                            {
                                dt.Rows.Add(tweet.Author.Name, tweet.Title);

                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            dt.Rows.Add(tweet.Author.Name, tweet.Title);
                        }

                        newTweets = true;
                        totalTweets++;
                        currentTweets++;

                        //}


                    }
                }
                if (newTweets)                                    /////showing tweets/////
                {

                    lblTweets.Text = "Showing " + totalTweets + " " + "Tweets";
                    
                }
                else
                {

                    
                    lblTweets.Text = " ";
                }                                                      /////refreshing results after 5 minutes interval/////
                
                if (this.WebPart.TweetsPerPageProp == 0)
                { gvTwitterSearch.AllowPaging = false; }
                else
                {
                    gvTwitterSearch.AllowPaging = true;
                    gvTwitterSearch.PageSize = Convert.ToInt32(this.WebPart.TweetsPerPageProp.ToString());
                }

                
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        ViewState["Data"] = dt;
                        Label4.Text = dt.Rows.Count.ToString();
                        gvTwitterSearch.DataSource = dt;                            /////binding datatable with gridview/////
                        gvTwitterSearch.DataBind();
                    }
                    else
                    {
                        gvTwitterSearch.DataSource = null;
                        gvTwitterSearch.DataBind();
                    }

                }
                lblNewTweets.Text = "";
            }
        }
        public string Read(string KeyName)
        {
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey sk1 = rk.OpenSubKey("SOFTWARE\\TWITTERWEBPART");
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                    return (string)sk1.GetValue(KeyName.ToUpper());
                }
                catch
                {
                    return null;
                }
            }
        }
        public bool Write(string KeyName, object Value)
        {
            try
            {
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey sk1 = rk.CreateSubKey("SOFTWARE\\TWITTERWEBPART");
                sk1.SetValue(KeyName.ToUpper(), Value);

                return true;
            }
            catch
            {
                return false;
            }
        }
        public static string EncryptText(string textToEncrypt)
        {
            byte[] results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider hashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = hashProvider.ComputeHash(UTF8.GetBytes("TwitterWebPart"));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider tDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            tDESAlgorithm.Key = TDESKey;
            tDESAlgorithm.Mode = CipherMode.ECB;
            tDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] dataToEncrypt = UTF8.GetBytes(textToEncrypt);

            // Step 5. Attempt to encrypt the string
            try
            {
                ICryptoTransform encryptor = tDESAlgorithm.CreateEncryptor();
                results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                tDESAlgorithm.Clear();
                hashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return Convert.ToBase64String(results);
        }
        public static string DecryptText(string textToDecrypt)
        {
            byte[] results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider hashProvider = new MD5CryptoServiceProvider();
            byte[] tDESKey = hashProvider.ComputeHash(UTF8.GetBytes("TwitterWebPart"));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider tDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            tDESAlgorithm.Key = tDESKey;
            tDESAlgorithm.Mode = CipherMode.ECB;
            tDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] dataToDecrypt = Convert.FromBase64String(textToDecrypt);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform decryptor = tDESAlgorithm.CreateDecryptor();
                results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                tDESAlgorithm.Clear();
                hashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return UTF8.GetString(results);
        }

        protected void btnkey_Click(object sender, EventArgs e)
        {
            string[] arr = new string[] {
                "C001E414-DF1A-4751-814C-6F85B7C81257",
                "FDCBEBD5-5153-4D2E-B797-05E942273B89",
                "747E1FC9-AB40-422D-ABB7-41D41BD48301",
                "2BCDC676-9D0F-448E-80C3-385149752288",
                "1A78159C-33F9-4CE2-8AC6-453ED024A893",
                "0FC5441E-ED85-4968-8DF4-F6138A172571",
                "567BE0A3-0FDD-4BF7-89A5-7AD756B0F661",
                "15B29B97-FC2F-46AA-9DD8-92F2065641B4",
                "521BC896-585C-47F5-9042-538C2CA8B57E",
                "5B51F9CF-ECA5-451F-AAB5-714BA89C66AD",
                "9171D373-B590-453B-A3EE-3FEE42447032",
                "194AF43E-4DD1-4C5E-8CE1-5DF1691851C8",
                "F045CD93-0555-40B4-A2A1-C94549DDF02A",
                "30B26EFA-DD56-43D4-95C0-E3276BD6A8A4",
                "746F5564-81D0-41E6-BAD1-DF60531A3FD7",
                "E7CD69F6-B7E5-4BA9-9A5A-D60367419DA8",
                "66B63CCD-5DE8-48EB-9BB1-8C5F3E222D79",
                "C963C4D1-CF6D-45C8-9E0F-D86EAF1B1081",
                "E7E1675F-A892-4A7B-A1BE-DF643F9A7303",
                "0EA762AF-521E-4318-9028-9CA455BBE431",
                "07C9D965-567A-41F0-95B4-08830F22DC4E",
                "75EDC219-39D3-4028-8E05-0FD99827B123",
                "3204F1F7-4FC9-4EF9-88C7-4E61D6BBECD0",
                "BE03AAC1-5214-4D91-9280-8F9950A1008B",
                "1D4FBB4D-FB1D-4CEB-85DA-49525A74A638",
                "AFE1AF3C-77A6-4026-AD33-9E627F92D85E",
                "F371CE05-A11B-434F-9FEA-F9E43C1DF91F",
                "1888200F-87CC-4859-A7E7-703BC1691EBB",
                "A5153AA5-F948-4736-91C5-755455B8A8F9",
                "B1C77E9A-DF60-4F4D-8C88-6D6737C2302B",
                "F4ABBF56-F8ED-48C8-98C9-93D1735E6840",
                "FD6E5D6C-8827-41B8-B831-AF7FA76B6EAC",
                "8DE856B9-B4E2-4847-937D-5CABA0260686",
                "28BA6FDD-354E-4618-A67C-E95A1790DBB5",
                "F9E9A358-34A3-4762-9263-D2D00BD88DA4",
                "BC3CC1F6-9585-4BD0-8ABC-C0E518A9EC8E",
                "72DF59CE-9554-4152-8625-EB0F57E252DC",
                "6D19D368-B87D-4970-B74C-FD4F3B04FB31",
                "A83D2A11-CAB7-4F2E-93DC-20F05F0A7689",
                "10CF4494-DCC3-448E-9832-C26FE58F0BB0",
                "E9E219B1-62D0-45E3-9022-6085E28321DC",
                "E8FED9DE-AA92-498A-A99D-E9BCBAC69938",
                "FDBE5994-B804-4864-BF77-7CC4F73DAC9E",
                "D92E6C7A-C807-4FB4-AEB1-EE876214544F",
                "7C522AFF-B29F-48FC-91E2-544F98697426",
                "A0968949-F61E-43C4-9233-DA34B42E3736",
                "791CD936-768D-4AF4-9D87-512F130AE599",
                "F831B95C-6B8B-433D-A5A2-D54233BA025D",
                "D6B9FA02-9170-4242-B9E2-01B9EF396855",
                "54E8F22C-1832-4C9B-86C6-E944EFD34866",
            };
            bool flag = false;
            string Input = txtKey.Text.Trim();
            for (int index = 0; index < arr.Length; index++)
            {
                if (Input == arr[index])
                {
                    string Key = EncryptText("Expiration");
                    string ExpirationDate = Read(Key);

                    //Create Registry
                    ExpirationDate = EncryptText(System.DateTime.Now.AddYears(1000).ToString());
                    Write(Key, ExpirationDate);
                    flag = true;
                    break;
                }
            }
            if (flag)
            {
                //hide txtkey and button and error message
                txtKey.Visible = false;
                btnkey.Visible = false;
                //show or enable
                txtboxSearch.Enabled = true;
                btnSearch.Enabled = true;
                btnRefresh.Enabled = true;
                btnClear.Enabled = true;
                lblExpire.Text = "";
            }
            else
            {
                // message
                lblExpire.Text = "Your key is invalid. Please try a valid key!!!";
                
            }
            txtKey.Text = "";
        }
        
    }
}
